import _ from 'lodash'
;(function (doc, win) {
  const docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'

  if (!doc.addEventListener) return

  const recalcAction = () => {
    const { availWidth, availHeight } = screen
    if (!availWidth) return
    // 用高度倒推设计宽度，兼容折叠屏横向对折
    let designHeight = Math.max(availWidth, availHeight)
    const screenRatio =
      availWidth > availHeight ? availWidth / availHeight : availHeight / availWidth
    let delta = 0
    const largeScreenRatio = 1.75
    const foldingScreenRatio = 1.2
    if (screenRatio < largeScreenRatio) {
      // 长宽比较贴近的，或许是折叠屏或ipad,这时候用短边做高,用短边算出设计宽度
      designHeight = Math.min(availWidth, availHeight)
      if (screenRatio > foldingScreenRatio) {
        // 折叠屏宽高相近，宽高差距较大的是ipad，适当放大一点字体大小
        delta = Math.floor((screenRatio - foldingScreenRatio) * 8)
      }
    }
    // 设计稿比值

    const designRatio = window['designWidth'] / window['designHeight']
    // 设计稿宽度
    const designWidth = designHeight * designRatio
    // 算出缩放比例
    const flexible = designWidth / 1600
    // 基础字体大小是14像素，最大不能放大1.2倍，取整20像素
    const rem = Math.floor(Math.min(flexible * 14, 20)) + delta
    docEl.style.fontSize = rem + 'px'
  }

  const recalc = _.debounce(recalcAction, 400, { trailing: true })
  win.addEventListener(resizeEvt, recalc, false)

  if (document.readyState === 'loading') {
    doc.addEventListener('DOMContentLoaded', recalcAction, false)
  } else {
    recalcAction()
  }
})(document, window)
